layui.use(['layer'],function () {
	var layer = layui.layer;
	$(function () {
	let $img = $(".form-item .captcha-graph-img img"); //获取图形验证码标签元素
	let sImageCodeId = ""; //uuid 字符串变量
	let $username = $('input[name="username"]');
	generateImageCode();

	$img.click(generateImageCode);

	$username.blur(function () {
		fn_check_username();
	});

	//生成图片UUID
	function generateUUID() {
		let d = new Date().getTime();
		if (window.performance && typeof window.performance.now === "function") {
			d += performance.now(); //use high-precision timer if available
		}
		let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			let r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		return uuid;
	}

	// 生成一个图片验证码的编号，并设置页面中图片验证码img标签的src属性
	function generateImageCode() {
		// 1、生成一个图片验证码随机编号
		sImageCodeId = generateUUID();
		// 2、拼接请求url /image_codes/<uuid:image_code_id>/
		let imageCodeUrl = "/image_codes/" + sImageCodeId + "/";
		// 3、修改验证码图片src地址
		$img.attr('src', imageCodeUrl)
	}

	//用户名验证
	function fn_check_username() {
		let sUsername = $username.val();  // 获取用户名字符串
		if (sUsername === "") {
			layer.tips('用户名不能为空！',$username,{tips:1});
			return
		}
		if (!(/^\w{5,20}$/).test(sUsername)) {
			layer.tips('请输入5-20个字符的用户名',$username,{tips:1});
			return
		}

		// 发送ajax请求，去后端查询用户名是否存在
		$.ajax({
			url: '/usernames/' + sUsername + '/',
			type: 'GET',
			contentType: 'json',
		})
			.done(function (res) {
				if (res.count !== 0) {
					layer.tips(res.username + '已注册，请重新输入！',$username,{tips:1})
				} else {
					layer.tips(res.username + '能正常使用！',$username,{tips:1})
				}
			})
			.fail(function () {
				layer.tips('服务器超时，请重试！',$username,{tips:1});
			});
	}
});
});

